package fregat.base.util;

import java.nio.ByteBuffer;

public class ByteWrapper {
  private ByteBuffer buffer;

  public ByteWrapper(byte[] bytes) {
    buffer = ByteBuffer.wrap(bytes);
  }

  public ByteWrapper(int length) {
    buffer = ByteBuffer.allocate(length);
  }

  public ByteWrapper(byte[] bytes, int offset, int length) {
    wrap(bytes, offset, length);
  }

  /**
   * Wraps a subsequence of the given binary data.
   * @param index Start of subsequence
   * @param length Length of subsequence
   * @param b Binary data
   */
  protected void wrap(byte[] b, int index, int length) {
    byte[] sequence = new byte[length];
    System.arraycopy(b, index, sequence, 0, Math.min(length,b.length));
    buffer = ByteBuffer.wrap(sequence);
  }


  public void setBit(int index, int bit, boolean value) {
    byte b = buffer.get(index);
    if (value) {
      b |= (1 << bit);
    } else {
      b &= ~(1 << bit);
    }
    buffer.put(index, b);
  }

  public boolean getBit(int index, int bit) {
    int value = buffer.get(index) & (1 << bit);
    return value != 0;
  }

  public void setByte(int index, byte value) {
    buffer.put(index, value);
  }
}
